package com.njust.RateMyTray_backend.config;

import com.njust.RateMyTray_backend.common.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component // 会被 Spring 容器管理
public class JwtAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    // 使用ThreadLocal来存储用户信息，确保线程安全
    private static final ThreadLocal<Claims> userClaims = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authHeader = request.getHeader("Authorization"); // 获取请求头中的 Authorization 字段

        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith("Bearer ")) {
            log.warn("请求头缺少或非法的Authorization Bearer token");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "认证失败：缺少或非法的Token");
            return false;
        }

        String token = authHeader.substring(7); // 从 Authorization 字段中提取 token
        try {
            Claims claims = jwtUtils.extractAllClaims(token);
            // 可以在这里添加更多的验证
            
            // 验证token是否过期
            if (jwtUtils.isTokenExpired(token)) {
                 log.warn("Token已过期: {}", token);
                 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "认证失败：Token已过期");
                 return false;
            }
            
            userClaims.set(claims);
            log.info("Token验证通过, 用户: {}", claims.getSubject());
            return true;
        } catch (Exception e) {
            log.error("Token解析或验证失败: {}", e.getMessage());
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "认证失败：无效的Token");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求结束后，清除ThreadLocal中的数据，防止内存泄漏
        userClaims.remove();
    }

    // 提供一个静态方法，方便业务层获取当前登录用户的信息
    public static Claims getCurrentUserClaims() {
        return userClaims.get();
    }
} 